package com.yxkj.syh.app.huarong.activities;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;

import androidx.fragment.app.FragmentTransaction;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.gyf.immersionbar.ImmersionBar;
import com.syh.app.basic.App;
import com.syh.app.basic.BuildConfig;
import com.syh.app.basic.base.BaseActivity;
import com.syh.app.basic.base.BaseFragment;
import com.syh.app.basic.bean.LiveDataEvent;
import com.syh.app.basic.config.BasicConstants;
import com.syh.app.basic.utils.ActivityManager;
import com.syh.app.basic.utils.Loog;
import com.syh.app.basic.utils.Tooast;
import com.yxkj.syh.app.huarong.activities.links.LinksFragment;
import com.yxkj.syh.app.huarong.util.UserManager;
import com.yxkj.syh.app.huarong.BR;
import com.yxkj.syh.app.huarong.R;
import com.yxkj.syh.app.huarong.activities.home.HomeFragment;
import com.yxkj.syh.app.huarong.activities.orders.OrdersFragment;
import com.yxkj.syh.app.huarong.activities.user.UserFragment;
import com.yxkj.syh.app.huarong.constants.ArouterPath;
import com.yxkj.syh.app.huarong.databinding.ActivityMainBinding;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

@Route(path = ArouterPath.MAIN_ACTIVITY)
public class MainActivity extends BaseActivity<ActivityMainBinding, MainVM> {

    private BaseFragment mCurrentFragment;
    private HomeFragment mHomeFragment;
    private OrdersFragment mOrdersFragment;
    private LinksFragment mLinksFragment;
    private UserFragment mUserFragment;

    @Override
    protected int getContentLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected int getViewModelId() {
        return BR.mainVM;
    }

    @Override
    protected boolean needImmersionBarInit() {
        ImmersionBar.with(this).fitsSystemWindows(false).statusBarDarkFont(true).transparentStatusBar().init();
        return false;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mHomeFragment = HomeFragment.newInstance();
        mOrdersFragment = OrdersFragment.newInstance();
        mLinksFragment = LinksFragment.newInstance();
        mUserFragment = UserFragment.newInstance();
        switchFragment(mHomeFragment);

        mVDBinding.llHome.setOnClickListener(menuClickListener);
        mVDBinding.llOrders.setOnClickListener(menuClickListener);
        mVDBinding.llLinks.setOnClickListener(menuClickListener);
        mVDBinding.llUser.setOnClickListener(menuClickListener);
        mVDBinding.llNewOrder.setOnClickListener(menuClickListener);
    }

    @Override
    protected void initData() {
        super.initData();
        EventBus.getDefault().register(this);
    }

    private void switchFragment(final BaseFragment targetFragment) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (!targetFragment.isAdded()) {
            if (mCurrentFragment != null) {
                transaction.hide(mCurrentFragment);
            }
            transaction.add(R.id.flContent, targetFragment, targetFragment.getClass().getSimpleName());
        } else {
            if (targetFragment == mCurrentFragment) return;
            transaction.hide(mCurrentFragment);
            transaction.show(targetFragment);
        }
        mCurrentFragment = targetFragment;
        transaction.commit();
    }

    View.OnClickListener menuClickListener = v -> {

        if (v.getId() != R.id.llNewOrder) {
            mVDBinding.ivMainHome.setImageResource(R.mipmap.ic_main_home_unselected);
            mVDBinding.ivMainOrder.setImageResource(R.mipmap.ic_main_orders_unselected);
            mVDBinding.ivMainLinks.setImageResource(R.mipmap.ic_main_links_unselected);
            mVDBinding.ivMainUser.setImageResource(R.mipmap.ic_main_user_unselected);
        }
        switch (v.getId()) {
            case R.id.llHome:
                switchFragment(mHomeFragment);
                mVDBinding.ivMainHome.setImageResource(R.mipmap.ic_main_home_selected);
                break;
            case R.id.llOrders:
                switchFragment(mOrdersFragment);
                mVDBinding.ivMainOrder.setImageResource(R.mipmap.ic_main_orders_selected);
                break;
            case R.id.llLinks:
                switchFragment(mLinksFragment);
                mVDBinding.ivMainLinks.setImageResource(R.mipmap.ic_main_links_selected);
                break;
            case R.id.llUser:
                switchFragment(mUserFragment);
                mVDBinding.ivMainUser.setImageResource(R.mipmap.ic_main_user_selected);
                break;
            case R.id.llNewOrder:
                ARouter.getInstance().build(ArouterPath.NEW_ORDER_ACTIVITY).navigation();
                break;
        }
    };

    boolean requestedOrdersSelect = false;
    boolean requestedUserSelect = false;

    @Override
    protected void onResume() {
        super.onResume();
        if (UserManager.getUserManager().getUser() == null) {
            ARouter.getInstance().build(ArouterPath.LOGIN_ACTIVITY).navigation();
            finish();
        } else {
            setAlias();//极光的


            if (requestedOrdersSelect) {
                requestedOrdersSelect = false;
                if (mCurrentFragment != mOrdersFragment) {
                    switchFragment(mOrdersFragment);
                    mVDBinding.ivMainHome.setImageResource(R.mipmap.ic_main_home_unselected);
                    mVDBinding.ivMainLinks.setImageResource(R.mipmap.ic_main_links_unselected);
                    mVDBinding.ivMainUser.setImageResource(R.mipmap.ic_main_user_unselected);
                    mVDBinding.ivMainOrder.setImageResource(R.mipmap.ic_main_orders_selected);
                }
            } else if (requestedUserSelect) {
                requestedUserSelect = false;
                if (mCurrentFragment != mUserFragment) {
                    switchFragment(mUserFragment);
                    mVDBinding.ivMainHome.setImageResource(R.mipmap.ic_main_home_unselected);
                    mVDBinding.ivMainLinks.setImageResource(R.mipmap.ic_main_links_unselected);
                    mVDBinding.ivMainUser.setImageResource(R.mipmap.ic_main_user_selected);
                    mVDBinding.ivMainOrder.setImageResource(R.mipmap.ic_main_orders_unselected);
                }
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LiveDataEvent liveDataEvent) {
        switch (liveDataEvent.what) {
            case BasicConstants
                    .EVENT_LOGIN_STATUS:
                ARouter.getInstance().build(ArouterPath.LOGIN_ACTIVITY).navigation();
                ActivityManager.getInstance().finishAllActivity();
                break;
            case BasicConstants
                    .EVENT_SELECT_ORDER_ALL:
                requestedOrdersSelect = true;
                break;
            case BasicConstants
                    .EVENT_SELECT_USER:
                requestedUserSelect = true;
                break;
        }
    }

    long last;

    @Override
    public void onBackPressed() {
        long c = System.currentTimeMillis();
        if (c - last > 1000) {
            last = c;
            Tooast.normalInfo("双击退出");
        } else {
            ActivityManager.getInstance().finishAllActivity();
        }
    }

    @Override
    protected void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }

    private void setAlias() {
//        JPushInterface.setAlias(App.getApplication(), 1, alias);
        // 调用 Handler 来异步设置别名
        if (UserManager.getUserManager().isSetedAlias()) {
            Loog.d("MainActivity", "用户" + UserManager.getUserManager().getUser().getRealName() + "," + UserManager.getUserManager().getUser().getId() + "已设置过Alias");
        } else {
            mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS));
        }
    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        String logs = "--";

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            switch (code) {
                case 0:
                    logs = "Set  alias success . alias = "+alias;
                    Log.i("MainActivity", logs);
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    UserManager.getUserManager().setedAlias();
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 10s.";
                    Log.i("MainActivity", logs);
                    // 延迟 10 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS), 1000 * 10);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e("MainActivity", logs);
            }
        }
    };
    private static final int MSG_SET_ALIAS = 1001;
    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    if (UserManager.getUserManager().getUser() != null) {//这里再作判断  防止进入6002 循环

                        String alias = UserManager.getUserManager().getUser().getId()+"";

                        Loog.d("MainActivity", "Set alias in handler. msg.obj = " + alias);
                        // 调用 JPush 接口来设置别名。
                        JPushInterface.setAlias(getApplicationContext(),
                                alias,
                                mAliasCallback);
                    }
                    break;
                default:
                    Log.i("MainActivity", "Unhandled msg - " + msg.what);
            }
        }
    };
}
